#!/bin/bash

#######  error code specification  #########
# Please update this documentation if new error code is added.
# 1   => reserved for script error
# 2   => bad usage
# 3   => bad user

PROG_NAME=$0
ACTION=$1

usage() {
    echo "Usage: $PROG_NAME {start|stop}"
    exit 2 # bad usage
}

if [ "$UID" -eq 0 ]; then
    echo "ERROR: can't run as root, please use: sudo -u admin $0 $@"
    exit 3 # bad user
fi

if [ $# -lt 1 ]; then
    usage
    exit 2 # bad usage
fi

APP_HOME=$(cd $(dirname ${BASH_SOURCE[0]})/..; pwd)
echo "APP_HOME : ${APP_HOME}"

source "${APP_HOME}/bin/setenv.sh"

start() {
	eval exec "$JAVA_HOME/bin/java -jar " \
		 "${SERVICE_OPTS}" \
		"${APP_HOME}/target/${APP_NAME}.jar" \
		-Djava.endorsed.dirs="$JAVA_ENDORSED_DIRS"  \
		-Djava.io.tmpdir="$SERVICE_TMPDIR" \
		"org.springframework.boot.loader.JarLauncher" \
		"$@" \
		>> "$SERVICE_OUT" 2>&1 "&"		

    # check server status 
	
    echo "INFO: ${APP_NAME} start success and service start up"
}

SHUT_DOWN_DOMAIN="127.0.0.1"
SHUT_DOWN_PORT = "8081"

stop() {
    eval "curl -u admin:admin -X POST http://${SHUT_DOWN_DOMAIN}:${SHUT_DOWN_PORT}/manage/shutdown" \
		 "$@" \
		 >> "$SERVICE_OUT" 2>&1 "&"	
	
	
	echo "INFO: ${APP_NAME} stop success and service stop "
}

# check previous pipe command exit code. if no zero, whill exit with previous pipe status.
check_first_pipe_exit_code() {
  local first_pipe_exit_code=${PIPESTATUS[0]};
  if test $first_pipe_exit_code -ne 0; then
    exit $first_pipe_exit_code;
  fi
}

main() {
    now=`date "+%Y-%m-%d %H:%M:%S"`
    echo "$now--------------------------APP_HOME:${APP_HOME}"

    echo "INFO: deploy log: ${APP_HOME}/logs/${APP_NAME}_deploy.log"

    case "$ACTION" in
        start)
            start
        ;;
        stop)
            stop
        ;;
        *)
            usage
        ;;
    esac
}

main | tee -a ${APP_HOME}/logs/${APP_NAME}_deploy.log; check_first_pipe_exit_code;
